package [package].config;


import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

/**
 * 移除阿里连接池 druid 底部广告
 *
 * @author [author]
 */
@Configuration
@ConditionalOnWebApplication
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(DruidStatProperties.class)
public class RemoveDruidAdConfig {

    @Bean
    public FilterRegistrationBean removeDruidAdFilterRegistration(DruidStatProperties druidStatProperties) {

        //获取web监控页面的配置参数
        DruidStatProperties.StatViewServlet statViewServlet = druidStatProperties.getStatViewServlet();
        //提取common.js的配置路径
        String pattern = statViewServlet.getUrlPattern() == null ? "/druid/**" : statViewServlet.getUrlPattern();
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");

        String filePath = "support/http/resources/js/common.js";

        //创建filter进行过滤
        Filter filter = (servletRequest, servletResponse, filterChain) -> {
            filterChain.doFilter(servletRequest, servletResponse);
            //重置缓冲区,相应头不会被重置
            servletResponse.resetBuffer();
            //获取common.js
            String text = Utils.readFromResource(filePath);
            //正则替换banner,除去底部广告信息
            text = text.replaceAll("<a.*?banner\"></a><br/>", "");
            text = text.replaceAll("powered.*?shrek.wang</a>", "");
            servletResponse.getWriter().write(text);
        };

        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(filter);
        filterRegistrationBean.addUrlPatterns(commonJsPattern);
        return filterRegistrationBean;
    }

}
